import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useThemeStore = defineStore('theme', () => {
  // 主题状态：'light' | 'dark' | 'auto'
  const theme = ref<'light' | 'dark' | 'auto'>('auto')
  
  // 系统主题检测
  const systemPrefersDark = ref(false)
  
  // 计算当前实际主题
  const currentTheme = computed(() => {
    if (theme.value === 'auto') {
      return systemPrefersDark.value ? 'dark' : 'light'
    }
    return theme.value
  })
  
  // 是否为深色模式
  const isDark = computed(() => currentTheme.value === 'dark')
  
  // 初始化主题检测
  const initTheme = () => {
    // 从localStorage读取保存的主题设置
    const savedTheme = localStorage.getItem('theme') as 'light' | 'dark' | 'auto'
    if (savedTheme && ['light', 'dark', 'auto'].includes(savedTheme)) {
      theme.value = savedTheme
    }
    
    // 检测系统主题偏好
    if (typeof window !== 'undefined' && window.matchMedia) {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      systemPrefersDark.value = mediaQuery.matches
      
      // 监听系统主题变化
      mediaQuery.addEventListener('change', (e) => {
        systemPrefersDark.value = e.matches
        applyTheme()
      })
    }
    
    // 应用主题
    applyTheme()
  }
  
  // 应用主题到DOM
  const applyTheme = () => {
    if (typeof document !== 'undefined') {
      const root = document.documentElement
      
      if (isDark.value) {
        root.classList.add('dark')
        root.classList.remove('light')
      } else {
        root.classList.add('light')
        root.classList.remove('dark')
      }
      
      // 设置meta标签用于移动端状态栏
      const metaThemeColor = document.querySelector('meta[name="theme-color"]')
      if (metaThemeColor) {
        metaThemeColor.setAttribute('content', isDark.value ? '#1a1a1a' : '#42b883')
      }
    }
  }
  
  // 切换主题
  const setTheme = (newTheme: 'light' | 'dark' | 'auto') => {
    theme.value = newTheme
    localStorage.setItem('theme', newTheme)
    applyTheme()
  }
  
  // 快速切换亮色/暗色（不包括auto）
  const toggleTheme = () => {
    if (theme.value === 'auto') {
      // 如果当前是auto，根据当前实际显示的主题来切换
      setTheme(isDark.value ? 'light' : 'dark')
    } else {
      setTheme(theme.value === 'light' ? 'dark' : 'light')
    }
  }
  
  return {
    theme,
    currentTheme,
    isDark,
    initTheme,
    setTheme,
    toggleTheme
  }
})